/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.unicauca.opentextbook.controladores;

import edu.unicauca.opentextbook.entidades.Usuario;
import edu.unicauca.opentextbook.fachadas.UsuarioFacade;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;

/**
 *
 * @author ADM_JMARTINEZ
 */
@ManagedBean(name = "loginController")
@SessionScoped
public class LoginController extends BaseController implements Serializable {

    //EJBs
    @EJB
    private UsuarioFacade usuarioFacade;
    //Variables
    private String nick;
    private String password;

    //Metodos
    public void iniciarSesion(ActionEvent event) {
        final RequestContext context = RequestContext.getCurrentInstance();
        boolean loggedIn;
        String ruta = "";

        final Usuario usuario = usuarioFacade.buscarUsuario(nick, password);

        if (usuario == null) {
            loggedIn = false;
            anadirMensajeError("Nick y/o Contraseña incorrectos...");

        } else {
            loggedIn = true;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuario", nick);
            ruta = "/openTextBook/faces/vistas/principal.xhtml";
            password = "";
        }

        context.addCallbackParam("loggedIn", loggedIn);
        context.addCallbackParam("ruta", ruta);
    }

    public void cerrarSesion() {
        final String ruta = "/openTextBook/faces/index.xhtml";
        final RequestContext context = RequestContext.getCurrentInstance();
        final FacesContext facesContext = FacesContext.getCurrentInstance();
        final HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        session.invalidate();
        context.addCallbackParam("loggetOut", true);
        context.addCallbackParam("ruta", ruta);
    }

    //Getters y Setters
    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
